//
//  ALTools.m
//  TestAfn2
//
//  Created by xujingjing on 16/7/8.
//  Copyright © 2016年 xujingjing. All rights reserved.
//

#import "ALTools.h"




@implementation ALTools

/**
 *  iOS 日常工作之常用宏定义大全:http://mp.weixin.qq.com/s?__biz=MjM5OTM0MzIwMQ==&mid=2652546295&idx=1&sn=3c0217a67e0cfbce8cc285cb1cc9b3c1&scene=0&key=77421cf58af4a653818f0497d39d6e0eb06895e18c1cda3adc71b0d38f43b63e5844f6300355ea1bd5c3f912bb609afb&ascene=7&uin=MTkzNjI2OTQxOA%3D%3D&devicetype=android-23&version=2603163b&nettype=WIFI&pass_ticket=yQLEn6MLEPjGdkhTGZ62Rg3Buoonej13lYrUEK2C1raTI5rnBZjoovER3jxkIS1T
 */




static ALTools *sharedManager = nil;

+ (ALTools *)sharedManager {
    
    @synchronized (self) {
        
        if (!sharedManager) {
            
            sharedManager = [[[self class] alloc] init];
            
        }
        
    }
    
    return sharedManager;
}



/**
*  压缩图片为data
*
*  @param imagedata 待压缩图片
*
*  @return NSData类型
*/





+(NSData *)dataWithImage:(UIImage *)image{

    UIImage *iamge = image;
    CGFloat kCompressionQuality = 1.0;
    NSData * data = UIImageJPEGRepresentation(iamge, kCompressionQuality );
    
    NSLog(@"图片上传大小：%luK",data.length/1024);
    NSInteger kb = data.length / 1024;
    CGFloat scale = 1;
    if (kb > 2048) {
        kb = kb / 2014;
        scale = 0.3;
    }else if(kb > 1024){
        scale = 0.5;
    }else if(kb > 200)
    {
        scale = 0.7;
    }
    if (scale < 1.0) {
        data     =  UIImageJPEGRepresentation(iamge, scale);
    }
    
    return data;

}






/**
*  压缩图片
*
*  @param image   待压缩图片
*
*  @return 压缩后的图片
*/
+(UIImage*)imageWithImage:(UIImage*)image
{

    UIImage *iamge = image;

    UIImageOrientation imageOrientation=iamge.imageOrientation;
   
    if(imageOrientation!=UIImageOrientationUp){
// 原始图片可以根据照相时的角度来显示，但UIImage无法判定，于是出现获取的图片会向左转９０度的现象。
    // 以下为调整图片角度的部分
    UIGraphicsBeginImageContext(iamge.size);
    [iamge drawInRect:CGRectMake(0, 0, iamge.size.width, iamge.size.height)];
    iamge = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    // 调整图片角度完毕
      }
    
    CGSize imagesize = iamge.size;
    //质量压缩系数
    CGFloat compressionQuality = 1;
    
    //如果大于两倍屏宽 或者两倍屏高
    if (iamge.size.width > 640 || iamge.size.height > 568*2) {
        compressionQuality = 0.5;
        //宽大于高
        if (iamge.size.width > iamge.size.height) {
            imagesize.width = 320*2;
            imagesize.height = iamge.size.height*imagesize.width/iamge.size.width;
        }else{
            imagesize.height = 568*2;
            imagesize.width = iamge.size.width*imagesize.height/iamge.size.height;
        }
    }else{
        compressionQuality = 0.6;
    }
    
    // Create a graphics image context
    UIGraphicsBeginImageContext(imagesize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,imagesize.width,imagesize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}



//裁剪图片
+ (UIImage *)cutImage:(UIImage*)image TargetIV:(UIImageView *)targetIV
{
//压缩图片
    CGSize newSize;
    CGImageRef imageRef = nil;

    if ((image.size.width / image.size.height) < (targetIV.frame.size.width /targetIV.frame.size.height)) {
      
        newSize.width = image.size.width;
      
        newSize.height = image.size.width * targetIV.frame.size.height / targetIV.frame.size.width;

        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));

        } else {
            
            newSize.height = image.size.height;
             
            newSize.width = image.size.height * targetIV.frame.size.width / targetIV.frame.size.height;
    
    
            imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
    
        }
    
    return [UIImage imageWithCGImage:imageRef];
}

//裁剪图片
+ (UIImage *)cutImage:(UIImage*)image TargetSize:(CGSize)targetSize
{
    //压缩图片
    CGSize newSize;
    CGImageRef imageRef = nil;
    
    if ((image.size.width / image.size.height) < (targetSize.width /targetSize.height)) {
        newSize.width = image.size.width;
        newSize.height = image.size.width * targetSize.height / targetSize.width;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
        
    } else {
        newSize.height = image.size.height;
        newSize.width = image.size.height * targetSize.width / targetSize.height;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
        
    }
    UIImage *reduceImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);//用完一定要释放，否则内存泄露
    return reduceImage;
}


+(void)ttAlert:(NSString *)message{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil];
        [alert show];
        
        
    });
    
}
+ (NSInteger)OSVersion
{
    static NSUInteger _deviceSystemMajorVersion = -1;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _deviceSystemMajorVersion = [[[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."] objectAtIndex:0] intValue];
    });
    return _deviceSystemMajorVersion;
}

//获取字符串长度
+(float)getStringWidth:(NSString *)text{
    //float height =0;
    CGRect frame = [text boundingRectWithSize:CGSizeMake(100, 100) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16]} context:nil];
    
    return frame.size.width;
}

//获取字符串长度
+(float)getStringWidth:(NSString *)text andSize:(CGSize)size andFont:(NSInteger)font{
    CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: FONT(font)} context:nil];
    
    return frame.size.width;
}

//获取字符串高度
+(float)getStringHeight:(NSString *)text andSize:(CGSize)size andFont:(NSInteger)font{
    
    if([text isEqualToString:@""]){
        return 0;
    }
    CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: FONT(font)} context:nil];
    if (frame.size.height == 0) {
        return 0;
    }
    return frame.size.height +10;
}
/**
	获取缓存路径
	@returns 缓存路径
 */
+ (NSString*)getCacheDirectory
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
    //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //return [[paths objectAtIndex:0]stringByAppendingPathComponent:@"Voice"];
}

/**
	判断文件是否存在
	@param _path 文件路径
	@returns 存在返回yes
 */
+ (BOOL)fileExistsAtPath:(NSString*)_path
{
    return [[NSFileManager defaultManager] fileExistsAtPath:_path];
}

/**
	删除文件
	@param _path 文件路径
	@returns 成功返回yes
 */
+ (BOOL)deleteFileAtPath:(NSString*)_path
{
    return [[NSFileManager defaultManager] removeItemAtPath:_path error:nil];
}

/**
	生成文件路径
	@param _fileName 文件名
	@param _type 文件类型
	@returns 文件路径
 */
+ (NSString*)getPathByFileName:(NSString *)_fileName ofType:(NSString *)_type
{
    NSString* fileDirectory = [[[self getCacheDirectory]stringByAppendingPathComponent:_fileName]stringByAppendingPathExtension:_type];
    return fileDirectory;
}

/**
 生成文件路径
 @param _fileName 文件名
 @returns 文件路径
 */
+ (NSString*)getPathByFileName:(NSString *)_fileName{
    NSString* fileDirectory = [[self getCacheDirectory]stringByAppendingPathComponent:_fileName];
    return fileDirectory;
}

+ (NSString*)makePhoneNumChangeState:(NSString *)phone{
    NSString *beginNum = [phone substringToIndex:3];
    NSString *lastNum = [phone substringFromIndex:7];
    return [NSString stringWithFormat:@"%@****%@",beginNum,lastNum];
}

+(BOOL)checkTel:(NSString *)str
{
    
    //1[0-9]{10}
    //^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$
    //    NSString *regex = @"[0-9]{11}";
    //NSString *regex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    NSString *regex = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    if (!isMatch) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入正确的手机号码" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
        return NO;
    }
    return YES;
}
+(NSInteger)caculateRowHeight:(NSArray *)array andFont:(NSInteger)font{
    NSInteger heightCount = 1;
    
    if (array.count>0) {
        CGRect frame = CGRectZero;
        frame.origin.x = SPACE;
        frame.origin.y = SPACE;
        NSInteger count = array.count;
        for (int i = 0; i<count; i++) {
            
            NSString *titleName = array[i];
            CGFloat btnWidth = [self getStringWidth:titleName andSize:CGSizeMake(SCREEN_WIDTH-20, 100) andFont:font]+10;
            frame.origin.x += SPACE+btnWidth;
            //第二列需要重置x,y
            if (frame.origin.x>=SCREEN_WIDTH) {
                frame.origin.x = SPACE+btnWidth;
                heightCount++;
            }
        }
    }else{
        return 0;
    }
    return heightCount;
}


@end
